package com.jin.webvideo.websocket.shareroom.entity;


public class BinMessage {
    public static final byte MAGIC = (byte) 0xb4;
    public static final byte VERSION = 0x00;
    // 1byte magic
    // 1byte version
    // 1byte type
    // 2byte length
    // 4byte maskkey
    // 4byte checksum
    // payload
    // 进度消息
    public static final byte TYPE_CONTROL_PROGRESS = 0x01;
    // 源信息
    public static final byte TYPE_CONTROL_SRC = 0x02;
    // 播放状态信息
    public static final byte TYPE_CONTROL_ISPLAY = 0x04;
    // 倍速信息
    public static final byte TYPE_CONTROL_SPEED = 0x08;

    public static final byte TYPE_CONTROL_GETTER = 0x10;

    public static final int BROADCAST_SYSTEM = 2;
    public static final int BROADCAST_EXCEPT_SELF = 1;
    public static final int BROADCAST_SEND_SELF = 0;

    public static final int CHECKSUM_LEN = 4;
    public static final int MASKKEY_LEN = 4;
    private byte type;
    private byte[] payload;
    private int broadcast = 0;
    /**
     * 是否为 Getter消息
     * @param message
     * @return true 是Getter， false是Setter
     */
    public static boolean isGetter(BinMessage message) {
        return (message.type & 0x10) != 0;
    }

    // 第一位为0 为控制消息
    public static boolean isUserMessage(BinMessage message) {
        return (message.type >> 7) == 0;
    }
    // 第一位为1 为用户消息
    public static boolean isSystemMessage(BinMessage message) {
        return (message.type >> 7) == 1;
    }


    public static BinMessage createMessage(byte type, byte[] data) {
        BinMessage message = new BinMessage(data, type);
        return message;
    }
    public static byte[] checksum(byte[] data) {
        byte[] cs = new byte[CHECKSUM_LEN];
        for (int i = 0, l = data.length; i < l; i++) {
            cs[i%CHECKSUM_LEN] = (byte) (cs[i%CHECKSUM_LEN] + data[i]);
        }
        return cs;
    }

    public static byte[] afterMask(byte[] mask, byte[] data) throws BadMessageException {
        if (mask.length != MASKKEY_LEN) {
            throw new BadMessageException();
        }
        byte[] temp = new byte[data.length];
        for (int i = 0, l = data.length; i < l; i++) {
            temp[i] = (byte) (data[i] ^ mask[i%MASKKEY_LEN]);
        }
        return temp;
    }


    private BinMessage(byte[] payload, byte type) {
        this.payload = payload;
        this.type = type;
    }

    public byte[] getPayload() {
        return payload;
    }

    public byte getType() {
        return type;
    }

    public int getBroadcast() {
        return broadcast;
    }

    public void setBroadcast(int broadcast) {
        this.broadcast = broadcast;
    }

    public boolean is(byte type) {
        return (this.type & type) != 0;
    }
}
